package com.recharge.web.controller;

import com.recharge.common.util.MD5Util;
import com.recharge.common.util.RedisUtil;
import com.recharge.common.util.http.HttpClientUtil;
import com.recharge.domain.vo.CardCallbackDO;
import com.recharge.domain.vo.CardDO;
import com.recharge.domain.vo.EncryptionCardDO;
import com.recharge.domain.vo.MerchantCallbakDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/api")
public class TestController {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 订单提交返回
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"request.html"})
    public String request(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println("======================================================================");
        System.out.println("测试桩[" + request.getMethod() + "]接收数据:");
        parameterMap.forEach((k, v) -> System.out.println(k + ":" + v[0] + ", "));
        System.out.println("======================================================================");
        // 请求上游流水号
        final String orderSerialNum = parameterMap.get("serialno")[0];
        // 上游返回流水号
        final String serialNum = (Math.random() + "").substring(3);

        // 调用异步返回
        new Thread(() -> sendBackByParam("51204464108", 0, orderSerialNum, serialNum))
                .start();

        //new Thread(() -> sendBackByParam("47738359819", 0, orderSerialNum, serialNum))
        //.start();

//        return "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
//                "<order>" +
//                "  <result>success</result>" + //通信状态
//                "  <code>00</code>" + //通信状态
//                "  <sporderid>" + orderSerialNum + "</sporderid>" + //合作商订单号
//                "  <orderid>" + serialNum + "</orderid>" + //系统订单号
//                "  <status>1000</status>" + //订单状态
//                "  <desc>创建订单成功</desc>" + //状态描述
//                "  <account>2009042800001</account>" + //扣款金额,单位：元
//                "  <fundbalance>100000</fundbalance>" + //账户余额
//                "</order>";
        return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<response>\n" +
                "    <code>00</code>\n" +
                "    <desc>交易成功</desc>\n" +
                "    <status>success</status>\n" +
                "    <amount>999</amount>\n" +
                "    <areaCode>330000</areaCode>\n" +
                "    <bizOrderId>"+serialNum+"</bizOrderId>\n" +
                "    <carrierType>2</carrierType>\n" +
                "    <itemFacePrice>30000</itemFacePrice>\n" +
                "    <itemId>216749</itemId>\n" +
                "    <itemName>全国电信话费30-ming</itemName>\n" +
                "    <price>29400</price>\n" +
                "    <serialno>"+orderSerialNum+"</serialno>\n" +
                "</response>";

//        return "{\n" +
//                "  \"status\": \"success\",\n" +
//                "  \"desc\": \"交易成功\",\n" +
//                "  \"code\": \"00\",\n" +
//                "  \"serialno\": \"" + orderSerialNum + "\",\n" +
//                "  \"bizOrderId\": \"" + serialNum + "\",\n" +
//                "  \"itemId\": \"216749\",\n" +
//                "  \"itemName\": \"全国电信话费30-ming\",\n" +
//                "  \"itemFacePrice\": \"30000\",\n" +
//                "  \"price\": \"29400\",\n" +
//                "  \"amount\": \"29400\",\n" +
//                "  \"carrierType\": \"2\",\n" +
//                "  \"areaCode\": \"330000\",\n" +
//                "  \"success\": true\n" +
//                "}";
    }


    /**
     * 订单提交返回
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"request_oil.html"})
    public String requestOil(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println("======================================================================");
        System.out.println("测试桩[" + request.getMethod() + "]接收数据:");
        parameterMap.forEach((k, v) -> System.out.println(k + ":" + v[0] + ", "));
        System.out.println("======================================================================");
        // 请求上游流水号
        final String orderSerialNum = parameterMap.get("serialno")[0];
        // 上游返回流水号
        final String serialNum = (Math.random() + "").substring(3);

        // 调用异步返回
        new Thread(() -> sendBackByParam("51241221244", 0, orderSerialNum, serialNum))
                .start();

        //new Thread(() -> sendBackByParam("47738359819", 0, orderSerialNum, serialNum))
        //.start();

//        return "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
//                "<order>" +
//                "  <result>success</result>" + //通信状态
//                "  <code>00</code>" + //通信状态
//                "  <sporderid>" + orderSerialNum + "</sporderid>" + //合作商订单号
//                "  <orderid>" + serialNum + "</orderid>" + //系统订单号
//                "  <status>1000</status>" + //订单状态
//                "  <desc>创建订单成功</desc>" + //状态描述
//                "  <account>2009042800001</account>" + //扣款金额,单位：元
//                "  <fundbalance>100000</fundbalance>" + //账户余额
//                "</order>";
        return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<response>\n" +
                "    <code>00</code>\n" +
                "    <desc>交易成功</desc>\n" +
                "    <status>success</status>\n" +
                "    <amount>999</amount>\n" +
                "    <areaCode>330000</areaCode>\n" +
                "    <bizOrderId>"+serialNum+"</bizOrderId>\n" +
                "    <carrierType>2</carrierType>\n" +
                "    <itemFacePrice>30000</itemFacePrice>\n" +
                "    <itemId>216749</itemId>\n" +
                "    <itemName>全国电信话费30-ming</itemName>\n" +
                "    <price>29400</price>\n" +
                "    <serialno>"+orderSerialNum+"</serialno>\n" +
                "</response>";

//        return "{\n" +
//                "  \"status\": \"success\",\n" +
//                "  \"desc\": \"交易成功\",\n" +
//                "  \"code\": \"00\",\n" +
//                "  \"serialno\": \"" + orderSerialNum + "\",\n" +
//                "  \"bizOrderId\": \"" + serialNum + "\",\n" +
//                "  \"itemId\": \"216749\",\n" +
//                "  \"itemName\": \"全国电信话费30-ming\",\n" +
//                "  \"itemFacePrice\": \"30000\",\n" +
//                "  \"price\": \"29400\",\n" +
//                "  \"amount\": \"29400\",\n" +
//                "  \"carrierType\": \"2\",\n" +
//                "  \"areaCode\": \"330000\",\n" +
//                "  \"success\": true\n" +
//                "}";
    }

    /**
     * 订单提交返回
     *
     * @param
     * @return
     */
    @RequestMapping(value = {"/merchant/callback.html"}, method = RequestMethod.POST)
    public String merchantCallBack(@RequestBody MerchantCallbakDO domain) {
        System.out.println("merchantCallBack API data:" + domain);
        return "ok";
    }

    /**
     * 订单提交返回
     *
     * @param
     * @return
     */
    @RequestMapping(value = {"/card/callback.html"}, method = RequestMethod.POST)
    public String cardCallBack(@RequestBody CardCallbackDO domain) {
        System.out.println("CardCallbackDO API data====================:" + domain);
        return "ok";
    }

    /**
     * 异步返回param
     */
    public static void sendBackByParam(String provideId, int count, String orderSerialNum, String serialNum) {

        HashMap<String, String> hashMap = new HashMap<>();

        String sign = "null";
        try {
            //{bizId}{downstreamSerialno}{ejId}{status}{userId}{privateKey}
            System.out.println("before_sign: " + "201" + orderSerialNum + serialNum + "2495067235286kdla5KWaVFf1DzadD778+Z4zFuOjzdh");
            sign = MD5Util.md5("201" + orderSerialNum + serialNum + "2" + "49506723528"+"t7IkHCDgbA1XMiPB7gVTxog5gVfGcU0g", 32);
        } catch (Exception e) {
            e.printStackTrace();
        }

        hashMap.put("userId", "49506723528");
        hashMap.put("bizId", "201");
        hashMap.put("ejId", serialNum);
        hashMap.put("downstreamSerialno", orderSerialNum);
        hashMap.put("status", "2");
        hashMap.put("sign", sign);
        hashMap.put("voucher", "4982344597230");

        String url = String.format("http://39.100.117.1/app/api/callBack/%s.html", provideId);
//        String url = String.format("http://127.0.0.1:9996/app/api/callBack/%s.html", provideId);
        System.out.println(String.format("第%s次发送回调: %s", ++count, url));
        String s = HttpClientUtil.doPost(url, hashMap);
        System.out.println("第" + count + "次返回: " + s);
        if (!"success".equals(s) && count < 3) {
            sendBackByParam(provideId, count, orderSerialNum, serialNum);
        }
        log.info("发送异步回调完成!" + url);
    }

    /**
     * 异步返回body
     */
    public static void sendBackByJson(String provideId, int count, String orderSerialNum, String serialNum) {

        String sign = "null";
        try {
            //{bizId}{downstreamSerialno}{ejId}{status}{userId}{privateKey}
            System.out.println("before_sign: " + "201" + orderSerialNum + serialNum + "2188123456");
            sign = MD5Util.md5("201" + orderSerialNum + serialNum + "100" + "188123456", 32);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = "{" +
                "\"userId\":\"188\"," +
                "\"bizId\":\"201\"," +
                "\"ejId\":" + serialNum + "," +
                "\"downstreamSerialno\":\"" + orderSerialNum + "\"," +
                "\"status\":\"2\"," +
                "\"sign\":\""+sign+"\"," +
                "\"voucher\":\"4982344597230\"" +
                "}";

        String url = String.format("http://127.0.0.1:9996/app/api/callBack/%s.html", provideId);
        System.out.println(String.format("第%s次发送回调: %s", ++count, url));
        String s = HttpClientUtil.doPostJson(url, json);
        System.out.println("第" + count + "次返回: " + s);
        if (!"success".equals(s) && count < 3) {
            sendBackByJson(provideId, count, orderSerialNum, serialNum);
        }
        log.info("发送异步回调完成!" + url);
    }

    /**
     * 查询余额返回
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"findBalance.html"}, method = RequestMethod.POST)
    public String findBalance(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach((k, v) -> System.out.println(k + "->" + v[0]));
        return "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                "<user>" +
                "  <result>0000</result>" + //通信状态
                "  <desc>查询成功</desc>" + //状态描述
                "  <fundbalance>10000</fundbalance>" + //合作商余额
                "</user>";
    }

    /**
     * 查询订单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"queryOrder.html"}, method = RequestMethod.POST)
    public String queryOrder(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach((k, v) -> System.out.println(k + "->" + v[0]));
        return "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                "<order>" +
                "  <result>0000</result>" + //通信状态
                "  <sporderid>2009042800001</sporderid>" + //合作商订单号
                "  <orderid>2020091819215429070</orderid>" + //系统订单号
                "  <status>success</status>" + //订单状态
                "  <desc>充值成功</desc>" + //状态描述
                "<voucherId>090428000003</voucherId>" + //充值凭证
                "</order>";
    }

    @RequestMapping(value = {"send.html"}, method = RequestMethod.GET)
    public String message() {
        redisTemplate.convertAndSend("queue", "aaaaaaaaa");
        return "ok";
    }

    public static void main(String[] args) {

        EncryptionCardDO encryptionCardDO = new EncryptionCardDO();
        encryptionCardDO.setEncryptionData("lbYzMQabQjB6xWhk805EiSF/hW62KdYPSM9Jm/0RQYkrBaD5iPTCjXXBtp88awgioD/Cic0P4UJkJi7s9BK3hQ9xki2YGPnb92qbn2gUByLiatLw+xHMvF+PmgiOqS5+6Ub1iNeWel3GeOUPbEvhRTCNZTOInjBtJBBM8H1zPR/hjIV0PAUmYHcNXBu7S955wR9keeeEkyissrJQNpJ1RHaaRSNglc8bS7CH7otMT7IVXyPC4BIMU1M/watoPECd7BSl8ZSF7qXlaZl3yGbwJuogTG/mKJ6UURCC49fDOd28kjFXCLYV1LLW6ddPgQGxR5yuI5KBmdc5tY+YTQdwNOXqZS5nt8bTbiSmBpdTzqovrxb+v/wMWUCI40zXA8AOcUQFGPam1GZKRh4C44STeAd86YqxqGUkUfYxQNQdzAK/fE2gJwuJVmRIAG3Riu96gh2wqB2/WfX12nNBc1vXptl1HWfgGJqgUToV/4kattVTgBMDAdbcHMb6rBGiaXl6hq+s8j6vwX9gd5wwfCywlgghB3RmR/hYXsBBsRtEErYFKx4fS01PrvfEz/XTs/QG5dkpI4Whk/3LqTdcvI/jlWHIts+vZN5fQk58kiVaCC77NadlJmX3AThAbgAbwA9oaxi9Z87SX4rGDDR8vv76q0hq9wXCC9O4KQALIHwQeZKtYp9gRqp+1NsHztH6SaDVXlPsZVkKtaOGv2qvPZsPY77nJoEOd6gRDIuroychi4rdWdWYNdA/gtamq08OzX5CUt0nxWvolzqGa60TwFzSIz5Ukmrjnlpzr9PzXf3q3eKYer7HsQ5xiCDgC50DYtJuXXQh5UdbKEMHPxX9G/rzffb4Z630NHJLTmgjs4VrzpGvbQY5oES7O9O8AiblYgySCA7TM+5xcBWlEs55ZpvrCcyppz+2Mcv/C+TDSzNx4jBQUZZ4/yn+cxL8APMrmzOjihcfZKSgwEwulicWj/Jv/NUJbpp0whgwnOl45v1qAuo=");
        encryptionCardDO.setProviderNo("60725862624");
    }

}
